<!--优选库位管理 -->
<script setup lang="ts">
import {
  getPage,
  getForm,
  add,
  update,
  deletes,
  getStoreBinOptions,
  getEngPlannerOptions,
  getEngBuyerOptions,
  getEngSalemanOptions,
} from "@/api/eng/engitem";
import { EngItemFormVO, EngItemQuery } from "@/api/eng/engitem/types";
import { ElMessage, ElMessageBox, ElForm } from "element-plus";

import { getModelDictOptions } from "@/api/sys/dict/index";

defineOptions({
  name: "Engitem",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const storeBinList = ref<OptionType[]>(); // 优先库位下拉数据源
let engEmpList = [];

let engEmp_isBuyer = ref<OptionType[]>();
let engEmp_isPlanner = ref<OptionType[]>();
let engEmp_isSaleMan = ref<OptionType[]>();

const queryParams = reactive<EngItemQuery>({
  pageNum: 1,
  pageSize: 10,
});

const updateTimeRange = ref("");
const pageList = ref<EngItemFormVO[]>();

watch(updateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startUpdateTime = newVal[0];
    queryParams.endUpdateTime = newVal[1];
  }
});

const dialog = reactive({
  title: "",
  visible: false,
});

//默认值
const formData = reactive<EngItemFormVO>({
  status: 1,
  mb: "M",
  it: "N",
  st: "A",
  netWeight: 0,
  packWeight: 0,
  packVolume: 0,
  packQty: 0,
  orderPolicy: 1,
  leadTime: 0,
  lotSizeDay: 0,
  fixedLeadTime: 0,
  changeBatch: 0,
  changeDays: 0,
  moq: 0,
  multiple: 1,
  yield: 1,
});

const rules = reactive({
  itemNo: [{ required: true, message: "请输入货号", trigger: "blur" }],
  itemName: [{ required: true, message: "请输入货名", trigger: "blur" }],
  mb: [{ required: true, message: "请输入制构代码", trigger: "blur" }],
  it: [{ required: true, message: "请输入类型代码", trigger: "blur" }],
  st: [{ required: true, message: "请输入状态代码", trigger: "blur" }],
  netWeight: [{ required: true, message: "请输入净重", trigger: "blur" }],
  packWeight: [{ required: true, message: "请输入包装重量", trigger: "blur" }],
  packVolume: [{ required: true, message: "请输入包装体积", trigger: "blur" }],
  packQty: [{ required: true, message: "请输入包装数量", trigger: "blur" }],
  orderPolicy: [{ required: true, message: "请输入计划策略", trigger: "blur" }],
  leadTime: [{ required: true, message: "请输入提前期", trigger: "blur" }],
  lotSizeDay: [{ required: true, message: "请输入批量天数", trigger: "blur" }],
  moq: [{ required: true, message: "请输入最低定量", trigger: "blur" }],
  multiple: [{ required: true, message: "请输入定量倍数", trigger: "blur" }],
  yield: [{ required: true, message: "请输入产出率", trigger: "blur" }],
});

/** 查询 */
async function handleQuery() {
  loading.value = true;
  await getPage(queryParams)
    .then(({ data }) => {
      pageList.value = data.list;
      console.dir(pageList.value);
      pageList.value?.forEach(function (val, idx) {
        let engMb = engDictOptions.value?.filter(function (val2, idx2) {
          return val2.typeCode === "eng_mb" && val2.value === val.mb;
        });
        if (engMb.length > 0) val.mbLabel = engMb[0].label;

        let engIt = engDictOptions.value?.filter(function (val2, idx2) {
          return val2.typeCode === "eng_it" && val2.value === val.it;
        });
        if (engIt.length > 0) val.itLabel = engIt[0].label;

        let engst = engDictOptions.value?.filter(function (val2, idx2) {
          return val2.typeCode === "eng_st" && val2.value === val.st;
        });
        if (engst.length > 0) val.stLabel = engst[0].label;

        let engop = engDictOptions.value?.filter(function (val2, idx2) {
          return val2.typeCode === "eng_op" && val2.value == val.orderPolicy;
        });
        if (engop.length > 0) val.opLabel = engop[0].label;
      });

      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  updateTimeRange.value = "";
  queryParams.pageNum = 1;
  queryParams.startUpdateTime = undefined;
  queryParams.endUpdateTime = undefined;
  queryParams.keywords = undefined;
  handleQuery();
}

/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开表单弹窗
 *
 * @param id ID
 */
async function openEditDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改信息";
    getForm(id).then(({ data }) => {
      Object.assign(formData, data);
      console.log(formData);
    });
  } else {
    dialog.title = "新增";
  }

  //加载下拉数据
  await loadStoreBinOptions();
  await loadEngEmpOptions();
}

/**  表单提交 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
      const id = formData.id;
      if (id) {
        update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**  重置 表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

/** 删除  */
function handleDelete(id?: number) {
  const idStrs = [id || ids.value].join(",");
  if (!idStrs) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deletes(idStrs).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

/** 加载优选库位下拉数据源 */
async function loadStoreBinOptions() {
  getStoreBinOptions().then((response) => {
    storeBinList.value = response.data;
  });
}

/** 加载工程员工下拉数据源 */
async function loadEngEmpOptions() {
  const queryParams = reactive<EngItemQuery>({
    pageNum: 1,
    pageSize: 10,
    isBuyer: 1,
  });

  getEngPlannerOptions().then((response) => {
    engEmp_isPlanner.value = response.data;

    // engEmp_isPlanner.value = engEmpList.filter(function (item) {
    //   return item.type2 === 1;
    // });

    console.log(engEmp_isPlanner);
  });

  getEngBuyerOptions().then((response) => {
    engEmp_isBuyer.value = response.data;

    console.log(engEmp_isBuyer);
  });

  getEngSalemanOptions().then((response) => {
    engEmp_isSaleMan.value = response.data;

    console.log(engEmp_isSaleMan);
  });
}

const engDictOptions: Ref<OptionType[]> = ref([]); // 字典下拉数据源

/** 加载工程字典下拉数据源 */
async function loadEngModelDictOptions() {
  // 根据字典类型编码(modelType)获取字典选项
  getModelDictOptions("eng_").then((response) => {
    engDictOptions.value = response.data;
  });
}

const dictDataDialog = reactive({
  title: "",
  visible: false,
});

/** 启动执行  */
onMounted(async () => {
  await loadEngModelDictOptions();
  console.dir(engDictOptions);

  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <!--查询条件 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="name">
          <el-input
            v-model="queryParams.keywords"
            placeholder="货号/货名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="更新时间">
          <el-date-picker
            class="!w-[240px]"
            v-model="updateTimeRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <!--功能按钮 -->
      <template #header>
        <el-button
          v-hasPerm="['eng:engitem:add']"
          type="success"
          @click="openEditDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          v-hasPerm="['eng:engitem:del']"
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        v-loading="loading"
        highlight-current-row
        :data="pageList"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="货号" prop="itemNo" width="140" />
        <el-table-column label="货名" prop="itemName" width="160" />
        <el-table-column label="机型" prop="model" width="80" />
        <el-table-column label="规格" prop="itemSpec" width="150" />
        <el-table-column label="颜色" prop="itemColor" width="100" />
        <el-table-column label="单位" prop="unit" width="100" />
        <el-table-column label="制构" prop="mbLabel" width="140" />
        <el-table-column label="类型" prop="itLabel" width="120" />
        <el-table-column label="状态" prop="stLabel" width="100" />
        <el-table-column label="是否检验" prop="isInspect" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.isInspect === 1" type="success">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="能力(小时)" prop="capacity" width="100" />
        <el-table-column label="模腔" prop="cavity" width="100" />

        <el-table-column label="净重" prop="netWeight" width="100" />
        <el-table-column label="水口/浇道" prop="rWeight" width="100" />
        <el-table-column label="包装重量(公斤)" prop="packWeight" width="100" />
        <el-table-column
          label="包装体积(立方米)"
          prop="packVolume"
          width="100"
        />
        <el-table-column label="包装类型" prop="packType" width="100" />

        <el-table-column label="包装数量" prop="packQty" width="100" />
        <el-table-column label="计划员" prop="planner" width="100" />
        <el-table-column label="采购员" prop="buyer" width="100" />
        <el-table-column label="销售员" prop="salesman" width="100" />
        <el-table-column label="计划策略" prop="opLabel" width="145" />
        <el-table-column label="固定提前期" prop="fixedLeadTime" width="100" />
        <el-table-column label="变动批量" prop="changeBatch" width="100" />
        <el-table-column label="批量变动天数" prop="changeDays" width="100" />
        <el-table-column label="提前期(天)" prop="leadTime" width="100" />
        <el-table-column label="批量天数" prop="lotSizeDay" width="100" />
        <el-table-column label="最低定量" prop="moq" width="100" />
        <el-table-column label="定量倍数" prop="multiple" width="100" />
        <el-table-column label="产出率" prop="yield" width="100" />

        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" align="center" />
        <el-table-column label="更新者" prop="updateName" align="center" />
        <el-table-column
          label="更新时间"
          prop="updateTime"
          align="center"
          width="160"
        />
        <el-table-column fixed="right" label="操作" align="center" width="160">
          <template #default="scope">
            <el-button
              v-hasPerm="['eng:engitem:edit']"
              type="primary"
              link
              size="small"
              @click.stop="openEditDialog(scope.row.id)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-hasPerm="['eng:engitem:del']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 弹出窗口 form -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="货号" prop="itemNo">
              <el-input v-model="formData.itemNo" placeholder="请输入货号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货名" prop="itemName">
              <el-input v-model="formData.itemName" placeholder="请输入货名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机型" prop="model">
              <el-input v-model="formData.model" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="图号" prop="drawingNo">
              <el-input v-model="formData.drawingNo" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货规格" prop="itemSpec">
              <el-input v-model="formData.itemSpec" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="颜色" prop="itemColor">
              <el-input v-model="formData.itemColor" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <dictionary v-model="formData.unit" type-code="eng_unit" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制构代码" prop="mb">
              <dictionary v-model="formData.mb" type-code="eng_mb" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货号类型" prop="it">
              <dictionary v-model="formData.it" type-code="eng_it" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="货号状态" prop="st">
              <dictionary v-model="formData.st" type-code="eng_st" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否检验" prop="isInspect">
              <el-radio-group v-model="formData.isInspect">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="能力" prop="capacity">
              <el-input v-model="formData.capacity" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="模腔" prop="cavity">
              <el-input v-model="formData.cavity" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="净重" prop="netWeight">
              <el-input v-model="formData.netWeight" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="水口/浇道" prop="runnerWeight">
              <el-input v-model="formData.runnerWeight" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="包装重量" prop="packWeight">
              <el-input v-model="formData.packWeight" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="包装体积" prop="packVolume">
              <el-input v-model="formData.packVolume" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="包装类型" prop="packType">
              <el-input v-model="formData.packType" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="包装数量" prop="packQty">
              <el-input v-model="formData.packQty" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划员" prop="planner">
              <el-select v-model="formData.planner" placeholder="请选择">
                <el-option
                  v-for="item in engEmp_isPlanner"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                /> </el-select
            ></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购员" prop="buyer">
              <el-select v-model="formData.buyer" placeholder="请选择">
                <el-option
                  v-for="item in engEmp_isBuyer"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="销售员" prop="salesman">
              <el-select v-model="formData.salesman" placeholder="请选择">
                <el-option
                  v-for="item in engEmp_isSaleMan"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划策略" prop="orderPolicy">
              <dictionary v-model="formData.orderPolicy" type-code="eng_op" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="固定提前期" prop="fixedLeadTime">
              <el-input v-model="formData.fixedLeadTime" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="变动批量" prop="changeBatch">
              <el-input v-model="formData.changeBatch" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批量变动天数" prop="changeDays">
              <el-input v-model="formData.changeDays" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提前期" prop="leadTime">
              <el-input v-model="formData.leadTime" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="批量天数" prop="lotSizeDay">
              <el-input v-model="formData.lotSizeDay" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最低定量" prop="moq">
              <el-input v-model="formData.moq" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="定量倍数" prop="multiple">
              <el-input v-model="formData.multiple" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="产出率" prop="yield">
              <el-input v-model="formData.yield" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="优选库位" prop="storebin">
              <el-select v-model="formData.storebin" placeholder="请选择">
                <el-option
                  v-for="item in storeBinList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="22">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                placeholder="备注"
                :autosize="{ minRows: 2, maxRows: 4 }"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
